<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNum">
        <el-input
          v-model="queryParams.orderNum"
          placeholder="请输入订单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户" prop="customerId">
        <el-select
          v-model="queryParams.customerId"
          placeholder="客户"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.customerName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售时间" prop="sellTime">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="设备状态" prop="deviceState">
        <el-radio-group v-model="queryParams.deviceState">
          <el-radio :label=0>待入库</el-radio>
          <el-radio :label=1>设备售出</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="orderNum" />
      <el-table-column label="客户" align="center" prop="customer.customerName" />
      <el-table-column label="销售时间" align="center" prop="sellTime" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sellTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单金额" align="center" prop="orderMoney" />
      <el-table-column label="付款方式" align="center" prop="payMethod">
        <template slot-scope="scope">
          <span v-if="scope.row.payMethod == 0">全款</span>
          <span v-if="scope.row.payMethod == 1">分期付款</span>
        </template>
      </el-table-column>
      <el-table-column label="设备状态" align="center" prop="deviceState">
        <template slot-scope="scope">
          <span v-if="scope.row.deviceState == 0">待入库</span>
          <span v-if="scope.row.deviceState == 1">设备售出</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1050px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="客户" prop="customerId">
          <el-select
            v-model="form.customerId"
            placeholder="请选择客户"
            clearable
            size="small"
            style="width: 240px"
          >
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :label="item.customerName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="销售时间" prop="sellTime">
          <el-date-picker
            v-model="form.sellTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="订单金额" prop="orderMoney">
          <el-input-number :controls="false" v-model="form.orderMoney" placeholder="请输入订单金额" :min="0" @blur="downOrderMoneyBlur(form.orderMoney)"/> 元
        </el-form-item>
        <el-form-item label="付款方式" prop="payMethod">
          <el-radio-group v-model="form.payMethod" @change="changeHandler">
            <el-radio class="radio" label="0">全款</el-radio>
            <el-radio class="radio" label="1">分期付款</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="付款时间" prop="payTime" v-show="form.payMethod==='0'">
          <el-date-picker
            v-model="form.payTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <div  v-if="form.payMethod==='1'">
          <el-row>
            <el-col :span="12">
              <el-form-item label="首付款" prop="downPayment">
                <el-input-number :controls="false" v-model="form.downPayment" placeholder="请输入首付款" :min="0" @blur="downPayBlur()"/>元
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="余额：" v-if="form.payMethod==='1'">
                {{balance}}
              </el-form-item>
            </el-col>
          </el-row>
          <div>
            <el-form-item label="付款分期">
              <el-form-item style="margin-bottom:8px;" v-for="(domain, index) in form.orderSpreadList"
              >
                第{{domain.spreadNum}}<el-input-number :prop="'orderSpreadList.'+ index + '.spreadNum'" v-model="domain.spreadNum" style="width: 100px" :min="0" disabled v-show="false"/>期&nbsp;&nbsp;&nbsp;<el-date-picker type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" v-model="domain.repayTime"></el-date-picker>&nbsp;&nbsp;还款&nbsp;&nbsp;<el-input-number  :controls="false" :prop="'orderSpreadList.'+ index + '.repayMoney'" style="width: 150px" v-model="domain.repayMoney" :min="0" @blur="repayMoneyBlur(domain.repayMoney,index)"/>元
                <i v-if="index === 0" class="el-icon-circle-plus" style="font-size:22px;margin:0 20px 0 5px;" @click="addDomain"></i> <i v-else style="font-size:22px;margin:0 20px 0 5px;" class="el-icon-remove" @click="removeDomain(index)"></i>
                <el-radio-group v-model="domain.repayState">
                  <el-radio-button label="1">未还款</el-radio-button>
                  <el-radio-button label="0">已还款</el-radio-button>
                </el-radio-group>
                </el-form-item>
            </el-form-item>
          </div>
        </div>
        <el-form-item label="设备状态" prop="deviceState">
          <el-radio-group v-model="form.deviceState" @change="changeStateHandler">
            <el-radio class="radio" label="0">待入库</el-radio>
            <el-radio class="radio" label="1">设备售出</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出售设备" v-if="form.deviceState === '1'">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleDeviceAdd"
              >选择设备</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleOrderDeviceDelete"
              >批量删除</el-button>
            </el-col>
          </el-row>
          <el-table v-loading="orderDeviceLoading" :data="orderDeviceList" @selection-change="handleSelectionOrderDeviceChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="设备名称" align="center" prop="deviceName" />
            <el-table-column label="设备编码" align="center" prop="deviceCode" />
            <el-table-column label="设备批次" align="center" prop="deviceBath" />
            <el-table-column label="产品类型" align="center" prop="product.productName" />
          </el-table>
          <el-dialog :title="addDevicetitle" :visible.sync="deviceAddOpen" width="1050px" append-to-body :showClose="false">
            <el-form label-width="40px">
              <div class="app-container">
                  <!--设备数据-->
                    <el-form :model="queryDeviceParams" ref="queryDeviceForm" :inline="true" v-if="showDeviceSearch" label-width="68px">
                      <el-form-item label="设备名称" prop="deviceName">
                        <el-input
                          v-model="queryDeviceParams.deviceName"
                          placeholder="请输入设备名称"
                          clearable
                          size="small"
                          @keyup.enter.native="handleDeviceQuery"
                        />
                      </el-form-item>
                      <el-form-item label="设备编码" prop="deviceCode">
                        <el-input
                          v-model="queryDeviceParams.deviceCode"
                          placeholder="请输入设备编码"
                          clearable
                          size="small"
                          @keyup.enter.native="handleDeviceQuery"
                        />
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDeviceQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetDeviceQuery">重置</el-button>
                      </el-form-item>
                    </el-form>

                    <el-table v-loading="deviceLoading" :data="deviceList" @selection-change="handleSelectionDeviceChange">
                      <el-table-column type="selection" width="55" align="center" />
                      <el-table-column label="设备名称" align="center" prop="deviceName" />
                      <el-table-column label="设备编码" align="center" prop="deviceCode" />
                      <el-table-column label="产品类型" align="center" prop="product.productName" />
                      <el-table-column label="设备批次" align="center" prop="deviceBath" />
                      <el-table-column label="设备描述" align="center" prop="deviceDesc" />
                    </el-table>

                    <pagination
                      v-show="deviceTotal>0"
                      :total="deviceTotal"
                      :page.sync="queryDeviceParams.pageNum"
                      :limit.sync="queryDeviceParams.pageSize"
                      @pagination="getDeviceList"
                    />
              </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitDeviceForm">确 定</el-button>
              <el-button @click="cancelDevice">取 消</el-button>
            </div>
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/system/order";
import { listCustomer} from "@/api/system/customer";
import { listDevice,listDeviceByIds,listDeviceById} from "@/api/system/device";
export default {
  name: "Order",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      orderDeviceIds:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      showDeviceSearch:true,
      devTmpList:[],
      // 总条数
      total: 0,
      deviceTotal:0,
      // 订单表格数据
      orderList: [],
      deviceList: [],
      // 弹出层标题
      title: "",
      addDevicetitle:"",
      // 是否显示弹出层
      open: false,
      deviceAddOpen: false,
      //订单金额上一次输入得值
      orderMoneyOld:0,
      //首付款上一次输入得值
      downPaymentOld:0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNum: null,
        customerId: null,
        sellTime: null,
        orderMoney: null,
        payMethod: null,
        payTime: null,
        deviceState: null,
        downPayment: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      },
      queryDeviceParams:{
        pageNum: 1,
        pageSize: 10,
        deviceName: null,
        deviceCode: null,
        isSell:"0"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderNum: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ],
        customerId: [
          { required: true, message: "客户不能为空", trigger: "blur" }
        ],
        orderMoney:[
          { required: true, message: "订单金额不能为空", trigger: "blur" }
          ,{
            validator: function (rule, value, callback) {
              if (value) {
                callback();
              } else {
                let tip = "";

                if (value * 1 === 0) {
                  tip = "订单金额应大于0"
                }
                if (tip) {
                  callback(new Error(tip));
                } else {
                  callback();
                }
              }
            }, trigger: "blur"
          }
        ],
        downPayment:[
          { required: true, message: "首付款不能为空", trigger: "blur" }
          ,{
            validator: function (rule, value, callback) {
              if (value) {
                callback();
              } else {
                let tip = "";
                if (value * 1 === 0) {
                  tip = "首付款金额应大于0"
                }
                if (tip) {
                  callback(new Error(tip));
                } else {
                  callback();
                }
              }
            }, trigger: "blur"
          }
        ]
      },
      // 日期范围
      dateRange: [],
      customerList:[],
      qkShow:false,
      fqShow:false,
      balance:0,
      iconClass:"",
      deviceLoading:true,
      orderDeviceLoading:true,
      orderDeviceList:[]
    };
  },
  created() {
    this.getList();
    this.getCustomerList();
  },
  methods: {
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.addDateRange(this.queryParams,this.dateRange,"sellTime")).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    addDomain(){
      let obj= {};
      obj['spreadNum'] = this.form.orderSpreadList.length + 1;
      obj['repayTime'] = '';
      obj['repayMoney'] = 0;
      obj['repayState'] = "1";
      this.form.orderSpreadList.push(obj)
    },
    removeDomain(index){
      this.balance = this.balance + parseInt(this.form.orderSpreadList[index].repayMoney);
      this.form.orderSpreadList.splice(index, 1);
      for (var i = 0;i < this.form.orderSpreadList.length;i++){
        this.form.orderSpreadList[i].spreadNum = i +1
      }
    },
    downPayBlur(){
      if(parseInt(this.form.orderMoney) - parseInt(this.form.downPayment) >= 0){
        this.balance = this.balance + this.downPaymentOld - parseInt(this.form.downPayment)
      }
      this.downPaymentOld = this.form.downPayment
    },
    repayMoneyBlur(value,index){
      if(this.form.orderSpreadList.length > 0) {
        var money = 0;
        for (var i = 0; i < this.form.orderSpreadList.length; i++) {
          money += parseInt(this.form.orderSpreadList[i].repayMoney)
        }
        this.balance = this.form.orderMoney - this.form.downPayment - parseInt(money)
      }
    },
    downOrderMoneyBlur(){
      let that = this
      that.balance = this.form.orderMoney
        if(this.form.orderSpreadList.length > 0) {
          var money = 0;
          for (var i = 0; i < this.form.orderSpreadList.length; i++) {
            money += parseInt(this.form.orderSpreadList[i].repayMoney)
          }
          this.balance = that.balance - parseInt(this.form.downPayment) - parseInt(money)
        }
    },
    /** 查询客户列表 */
    getCustomerList() {
      this.loading = true;
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelDevice() {
      this.deviceAddOpen = false;
      //this.form.deviceIds = [];
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderNum: null,
        customerId: null,
        sellTime: null,
        orderMoney: null,
        payMethod: "0",
        payTime: null,
        deviceState: "0",
        downPayment: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        orderSpreadList:[],
        deviceIds:[]
      };
      this.balance = 0
      this.downPaymentOld = 0
      this.resetForm("form");
    },
    changeHandler(value){
      if(value === "0"){
        this.form.orderSpreadList = []
      }else{
        this.addDomain();
        if(this.form.orderMoney > 0){
          this.balance = this.form.orderMoney;
        }
      }
    },
    changeStateHandler(value){
      this.orderDeviceList = [];
      if(value === "1"){
        if(this.form.deviceIds.length === 0){
          this.orderDeviceLoading = false;
        }
      }else{
        this.form.deviceIds = [];
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleDeviceQuery(){
      this.queryDeviceParams.pageNum = 1;
      this.getDeviceList();
    },
    getDeviceList(){
      this.queryDeviceParams.ids = this.form.deviceIds;
      this.deviceLoading = true;
      listDeviceById(this.queryDeviceParams).then(response => {
        this.deviceList = response.rows;
        this.deviceTotal = response.total;
        this.deviceLoading = false;
      });
    },
    getOrderDeviceList(){
      this.orderDeviceLoading = true;
      if(this.form.deviceIds.length > 0){
        listDeviceByIds(this.form.deviceIds).then(response => {
          this.orderDeviceList = response
          this.orderDeviceLoading = false;
        });
      }else{
        this.orderDeviceList = [];
        this.orderDeviceLoading = false;
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetDeviceQuery(){
      this.resetForm("queryDeviceForm");
      this.handleDeviceQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleSelectionDeviceChange(selection) {
      this.devTmpList = selection.map(item => item.id);
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleSelectionOrderDeviceChange(selection){
      this.orderDeviceIds = selection.map(item => item.id);
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    handleDeviceAdd(){
      //this.form.deviceIds = []
      this.deviceAddOpen = true;
      this.addDevicetitle = "选择设备"
      this.getDeviceList()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
        this.getOrderDeviceList()
      });

    },
    /** 提交按钮 */
    submitForm() {
      let that = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form.payMethod)
          if(this.form.payMethod === "1"){
            if(this.balance != 0){
              that.$modal.msgError("余额必须为 0")
              return
            }
          }
          if (that.form.id != null) {
            updateOrder(that.form).then(response => {
              that.$modal.msgSuccess("修改成功");
              that.open = false;
              that.getList();
            });
          } else {
            addOrder(that.form).then(response => {
              that.$modal.msgSuccess("新增成功");
              that.open = false;
              that.getList();
            });
          }
        }
      });
    },
    submitDeviceForm(){
      //将选中的设备添加到关联集合中
      for (let k = 0; k < this.devTmpList.length; k++) {
        let has = false;
        for (let j = 0; j < this.form.deviceIds.length; j++) {
          const dId = this.form.deviceIds[j];
          if(dId==this.devTmpList[k]){
            has=true;
          }
        }
        if(!has){
          this.form.deviceIds.push(this.devTmpList[k]);
        }
      }
      this.deviceAddOpen = false;
      this.getOrderDeviceList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleOrderDeviceDelete(){
      var temp01 = [];
      var temp02 = [];

      for (var i in this.orderDeviceIds) {
        temp01[this.orderDeviceIds[i]] = true;
      }
      for (var k in this.form.deviceIds) {
        if (!temp01[this.form.deviceIds[k]]) {
          temp02.push(this.form.deviceIds[k]);
        }
      }
      this.form.deviceIds = temp02
      this.getOrderDeviceList()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
